package com.google.screen;

import java.net.URLEncoder;
import java.util.concurrent.ExecutionException;

import com.google.zxing.client.android.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity {

	private EditText mEdtUser, mEdtPass;
	private CheckBox mCkbRemember;
	private SharedPreferences mSharedPref;
	private String mStrUsername, mStrPassword, mStrToken;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.control);
		mEdtUser = (EditText) findViewById(R.id.edtLoginUsername);
		mEdtPass = (EditText) findViewById(R.id.edtLoginPassword);
		mCkbRemember = (CheckBox) findViewById(R.id.ckbLoginRememberMe);

		mSharedPref = getSharedPreferences("BarcodePref", Context.MODE_PRIVATE);

		autoFillLogin();
	}

	private void autoFillLogin() {
		mStrUsername = getStringPref(mSharedPref, "username", "UserID");
		mStrPassword = getStringPref(mSharedPref, "password", "123456");
		mStrToken = getStringPref(mSharedPref, "token", "");
		mEdtUser.setText(mStrUsername);
		mEdtPass.setText(mStrPassword);
		if (getStringPref(mSharedPref, "rememberme", "0").equals("1")) {
			mCkbRemember.setChecked(true);
			if (mStrToken.equals("") == false) {
				Intent intent = new Intent(Login.this, Control.class);
				intent.putExtra("Token", mStrToken);
				startActivity(intent);
			}
		}
	}

	public void loginApp(View v) {
		ConnectionDetector connectDetector = new ConnectionDetector(this);
		if (!connectDetector.isConnectingToInternet()) {
			connectDetector.showSettingsAlert();
		} else {
			new AuthenLogin(this).execute();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		return true;
	}

	public String getStringPref(SharedPreferences sharedPref, String name,
			String valrtn) {
		return sharedPref.getString(name, valrtn);
	}

	public void setStringPref(SharedPreferences sharedPref, String name,
			String value) {
		SharedPreferences.Editor editor = sharedPref.edit();
		editor.putString(name, value);
		editor.commit();
	}

	public class AuthenLogin extends AsyncTask<String, Integer, String> {

		private Context mCtx;
		private ProgressDialog mProDialog;
		private Intent intent;

		public AuthenLogin(Context ctx) {
			mCtx = ctx;
			mProDialog = new ProgressDialog(mCtx);
			intent = new Intent(mCtx, Control.class);
		}

		@Override
		protected String doInBackground(String... params) {
			String strUsername = mEdtUser.getText().toString();
			String strPassword = mEdtPass.getText().toString();
			if (strUsername.equals("") || strPassword.equals("")) {
				return "fill";
			} else {
				StringBuffer uri = new StringBuffer(
						"http://www.chimrawa.com/service.php/authentication/login?");
				uri.append("user=" + URLEncoder.encode(strUsername)
						+ "&password=" + URLEncoder.encode(strPassword)
						+ "&code=");
				Log.i("uri", uri.toString());
				String param[] = new String[2];
				param[0] = uri.toString();
				param[1] = "login";

				Authentication authentication = new Authentication(mCtx);
				authentication.execute(param);
				try {
					ContentValues data = authentication.get();
					if (data != null) {
						if (data.getAsInteger("code") == 1
								&& data.getAsString("statusheader")
										.equals("ok")) {
							setStringPref(mSharedPref, "username", strUsername);
							setStringPref(mSharedPref, "password", strPassword);
							setStringPref(mSharedPref, "token",
									data.getAsString("token"));
							if (mCkbRemember.isChecked()) {
								setStringPref(mSharedPref, "rememberme", "1");
							} else {
								setStringPref(mSharedPref, "rememberme", "0");
							}
							intent.putExtra("Token", data.getAsString("token"));
							return "correct";
						} else {
							return "incorrect";
						}
					} else {
						return "notconnect";
					}
				} catch (InterruptedException e) {
					Log.i("InterruptedException", e.getMessage());
				} catch (ExecutionException e) {
					Log.i("ExecutionException", e.getMessage());
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			mProDialog.dismiss();
			if (result.equals("fill")) {
				Toast.makeText(mCtx, "Please fill username and password!",
						Toast.LENGTH_SHORT).show();
			}
			if (result.equals("incorrect")) {
				Toast.makeText(mCtx, "Please username or password incorrect!",
						Toast.LENGTH_SHORT).show();
			}
			if (result.equals("notconnect")) {
				Toast.makeText(mCtx, "Can't connect to server!",
						Toast.LENGTH_SHORT).show();
			}
			if (result.equals("correct")) {
				startActivity(intent);
				finish();
			}
		}

		@Override
		protected void onPreExecute() {
			mProDialog.setTitle("Login Authentication");
			mProDialog.setMessage("Connecting...");
			mProDialog.setCancelable(false);
			mProDialog.setCanceledOnTouchOutside(false);
			mProDialog.show();
			super.onPreExecute();
		}

	}
}
